#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@File ：ProductModel.py
@Author ：zqy
@Email : zqingy@work@163.com
@note:
"""

from sqlalchemy import Column, Integer, String, Numeric, Boolean, ForeignKey, Text
from sqlalchemy.orm import relationship

from application.util.MysqlUtil import mysql_db


class Product(mysql_db.Model):
    __tablename__ = 'product'
    __table_args__ = {'comment': '商品表'}

    id = Column(Integer, primary_key=True, comment="商品ID")
    name = Column(String(100), nullable=False, comment="商品名称")
    price = Column(Numeric(10, 2), nullable=False, comment="单价")
    image_url = Column(String(255), comment="商品图片")
    unit = Column(String(20), comment="单位")
    stock = Column(Integer, default=0, comment="库存")
    category_id = Column(Integer, ForeignKey('category.id'), comment="分类ID")
    is_hot = Column(Boolean, default=False, comment="是否热销")
    is_promo = Column(Boolean, default=False, comment="是否促销")
    is_new = Column(Boolean, default=False, comment="是否新品")
    sort = Column(Integer, default=999, comment="排序值")
    detail = Column(Text, default="", comment="商品详情")
    parameter = Column(Text, default="", comment="商品参数： 125g/个")
    service = Column(Text, default="", comment="售后保障：不支持退货")
    usable = Column(Boolean, default=True, comment="是否可用")

    category = relationship("Category", back_populates="products")
    cart_items = relationship("CartItem", back_populates="product")
    order_items = relationship("OrderItem", back_populates="product")
    product_coupons = relationship("ProductCoupon", back_populates="product")
    favorites = relationship("Favorite", back_populates="product", cascade="all, delete-orphan")


class Category(mysql_db.Model):
    __tablename__ = 'category'
    __table_args__ = {'comment': '商品分类表'}

    id = Column(Integer, primary_key=True, comment="分类ID")
    name = Column(String(50), nullable=False, comment="分类名称")
    sort = Column(Integer, default=0, comment="排序值")

    products = relationship("Product", back_populates="category")


# 商品-优惠券关联表
class ProductCoupon(mysql_db.Model):
    __tablename__ = 'product_coupon'

    id = Column(Integer, primary_key=True)
    product_id = Column(Integer, ForeignKey('product.id'), nullable=False)
    coupon_id = Column(Integer, ForeignKey('coupon.id'), nullable=False)

    product = relationship("Product", back_populates="product_coupons")
    coupon = relationship("Coupon", back_populates="product_coupons")
